package cm.mefobe.android.telecomcost.dao;

import java.security.InvalidParameterException;
import java.util.ArrayList;

import android.util.Log;
import cm.mefobe.android.telecomcost.TelecomCost;
import cm.mefobe.android.telecomcost.entities.Day;
import cm.mefobe.android.telecomcost.entities.Destination;
import cm.mefobe.android.telecomcost.entities.Time;
import cm.mefobe.android.telecomcost.entities.VoiceRate;

public class VoiceRateDAO {
	public static VoiceRate getCurrent(Destination destination) {
		VoiceRate currentVoiceRate = null;
		Time currentTime = Time.current();
		Day today = Day.today();

		Log.i("VoiceRateDAO",
				"we get the voice rate for the destination "
						+ destination.toString() + "...current time "
						+ currentTime.toString());

		ArrayList<VoiceRate> destinationVoiceRates = getDestinationVoiceRates(destination);

		int index = 0;

		while (index < destinationVoiceRates.size()) {
			VoiceRate rate = destinationVoiceRates.get(index);

			if (today.isInDays(rate.getDaysOfWeek())) {
				if ((rate.getStartTime().getHour() <= currentTime.getHour())
						&& (rate.getEndTime().getHour() >= currentTime
								.getHour())) {
					if (rate.getStartTime().getHour() == currentTime.getHour()) {
						if (rate.getStartTime().getMinute() <= currentTime
								.getMinute()) {
							return rate;
						}

						continue;
					}

					if (rate.getEndTime().getHour() == currentTime.getHour()) {
						if (rate.getEndTime().getMinute() >= currentTime
								.getMinute()) {
							return rate;
						}

						continue;
					}

					return rate;
				}
			}

			index++;
		}

		return null;
	}

	public static ArrayList<VoiceRate> getDestinationVoiceRates(Destination dest) {
		if (dest != null) {
			Log.i("VoiceRateDAO", "binding voice rates for the destination "
					+ dest.toString());
			ArrayList<VoiceRate> _voiceRates = TelecomCost.getDatabaseManager()
					.getVoiceRates();

			ArrayList<VoiceRate> destinationVoiceRates = new ArrayList<VoiceRate>();

			int index = 0;

			while (index < _voiceRates.size()) {
				if (_voiceRates.get(index).getDestinationLabel()
						.equals(dest.toString())) {
					destinationVoiceRates.add(_voiceRates.get(index));
				}
				index++;
			}

			return destinationVoiceRates;
		} else {
			throw new InvalidParameterException(
					"cannot load voice rates for a null destination");
		}
	}
}
